package com.astro.app;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.astro.business.UserManager;
import com.astro.domain.bean.User;
import com.astro.domain.bean.UserAccount;

public class LoadData {
	
	static final Logger log = Logger.getLogger(LoadData.class);
	
	public static void main(String[] args) {
		System.out.println("Program is starting...");
		try {
			// Initial application context
			System.out.println(" spring context is loading...");
			AppContext.setSpringContext(new ClassPathXmlApplicationContext(
					"spring-datasource-config.xml"));
			System.out.println(" spring context is loaded!");

			UserManager userManager = (UserManager) AppContext
					.getSpringContext().getBean("userManager");
			
			AppConfig appConfig = (AppConfig) AppContext.getSpringContext().getBean(AppConfig.class);
			
			try {

				Scanner scanner = new Scanner(new File(appConfig.getCSVPath()));
				
				scanner.useDelimiter(",");
				Set<String> emails = new HashSet<String>();
				
				scanner.nextLine();
				User user = null;
				while (scanner.hasNextLine()) 
				{
					String[] nextLine = scanner.nextLine().split(",");
					
					String email = nextLine[3].trim();
					String accountNo = nextLine[1].trim();

					if(!emails.contains(email)){
						emails.add(email);
						// Insert User
						user = new User();
						user.setEmail(email);
						user.setPassword(email);
	
						user.setStatus("1");
						userManager.addUser(user);
						user = userManager.getUserByEmail(email);
						
					}
					if(user != null) {
						//Insert User Account
						UserAccount userAccount = new UserAccount();
						userAccount.setAccountNo(accountNo);
						userAccount.setUserId(user.getUserId());
						userManager.addUserAccount(userAccount);
					}
				}
				scanner.close();
				
			} catch (Exception e) {
				e.printStackTrace();
			}

			// List Users
			List<User> userList = userManager.listUser();
			
			if (userList != null && userList.size() > 0)
				for (int i = 0; i < userList.size(); i++) {
					System.out.println("Index " + i + " : " + userList.get(i).getEmail());
					List<UserAccount> userAcounts = userManager.listUserAccount(userList.get(i).getUserId());
					System.out.println("AccountNo:");
					for (UserAccount userAccount : userAcounts) {
						System.out.println(userAccount.getAccountNo());
					}
				}

		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Done!");
	}
}
